package com.alan.sso.share.utils;

import com.alan.sso.share.bean.Constant;
import com.alan.sso.share.bean.SsoConfigData;
import com.alan.sso.share.bean.SsoUser;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @Auther: Alan liu
 * @Date: 2018/12/20 18:06
 * @Description: SsoCookieUtils
 */
public class SsoCookieUtils {

    public SsoCookieUtils() {
    }

    /**
     * @Author Alan liu
     * @Description 取cookies
     * @Date 10:33 2018/12/21
     * @param request
     * @param name
     * @return javax.servlet.http.Cookie
     **/
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Cookie[] arr$ = cookies;
            int len$ = cookies.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                Cookie c = arr$[i$];
                if (name.equals(c.getName())) {
                    return c;
                }
            }
        }

        return null;
    }

    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        return cookie == null ? null : cookie.getValue();
    }

    /**
     * 取出session并解密
     * @param request
     * @return
     */
    public static String retrieveSession(HttpServletRequest request) {

        String encryptedSession = getCookieValue(request, Constant.K_SESSION_KEY);
        if (StringUtils.isNotBlank(encryptedSession)) {
            String sessionCookie = SsoConfigData.newInstance().getAes().decryptStrFromBase64(encryptedSession);
            if (StringUtils.isNotBlank(sessionCookie)) {
                return sessionCookie;
            }
        }
        return null;
    }

    /**
     * 取出session并解密成SsoUser
     * @param request
     * @return
     */
    public static SsoUser parseStaffFromSessionCookie(HttpServletRequest request) {
        try {
            SsoUser ssoUser = JSONObject.parseObject(retrieveSession(request), SsoUser.class);
            return ssoUser != null && ssoUser.getId() != null && !StringUtils.isBlank(ssoUser.getUserName())  ? ssoUser : null;
        } catch (Exception var2) {
            return null;
        }
    }

}
